package dbadapters;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import commands.AddEmployee;
import entities.Employee;

/**
 * adapter for feeding all students and student information that is in the
 * database into the system on startup
 * 
 * @author eks691
 */
public class LoadEmployeesDB {

	/**
	 * loads all of the employees and their associated information from the db
	 * 
	 * @precond db does not have duplicate employees
	 */
	public LoadEmployeesDB() {

		try {
			Class.forName("org.postgresql.Driver");
		} catch (ClassNotFoundException cnfe) {
			System.out.println("Couldn't find driver class:");
			cnfe.printStackTrace();
		}

		Connection c = null;
		try {
			c = DriverManager.getConnection(
					"jdbc:postgresql://papyrus.usask.ca/cmpt370group00",
					"cmpt370group00", "an7x482d");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println(e);
		}

		Statement stmt = null;
		try {
			stmt = c.createStatement();
		} catch (SQLException e3) {
			// TODO Auto-generated catch block
			e3.printStackTrace();
		}

		// load all employee info
		ResultSet rs = null;
		try {
			rs = stmt.executeQuery("SELECT * FROM employees");
		} catch (SQLException e3) {
			// TODO Auto-generated catch block
			e3.printStackTrace();
		}
		try {
			while (rs.next()) {

				System.out.println(rs.getArray(1).toString());
				// make a new student for each row in db and add it to system
				Employee myEmployee = new Employee(Integer.parseInt(rs
						.getArray(1).toString()), rs.getArray(2).toString());
				myEmployee.setName(rs.getArray(3).toString());
				myEmployee.setBirthdate(rs.getArray(4).toString());
				myEmployee.setAddress(rs.getArray(5).toString());
				myEmployee.setPhoneNumber(rs.getArray(6).toString());
				myEmployee.setEmail(rs.getArray(7).toString());

				new AddEmployee(myEmployee);
			}
		} catch (SQLException e3) {
			// TODO Auto-generated catch block
			e3.printStackTrace();
		}

		// Cleanup
		try {
			rs.close();
		} catch (SQLException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}

		try {
			stmt.close();
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		try {
			c.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * test to see if loading works
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		new LoadEmployeesDB();

	}

}
